﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vuonthieunhi.Models;
using vuonthieunhi.Library;

namespace vuonthieunhi.Controllers
{
    public class BaseController : Controller
    {
        public BaseController()
          {
              //ViewData["FooterMenu"] = new CategoryDao().GetList();
              //ViewData["GlobalCategory"] = new SelectList(new CategoryDao().GetList(), "ID", "CategoryName", "");
              //ViewData["HotPartner"] = new PartnerDao().GetHotPartner();
              //ViewData["HotViewPartner"] = new PartnerDao().GetHotViewPartner();
              //ViewData["HotSalesPartner"] = new PartnerDao().GetSalesPartner();
              
          }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            HttpCookie orderCookie = base.Request.Cookies[Constants.ORDER_COOKIE];
            if (orderCookie == null)
            {
                orderCookie = new HttpCookie(Constants.ORDER_COOKIE);
            }
            ViewData["ShoppingCart"] = GetOrderList().OrderBy(q => q.ProductName).ToList();
        }


        private List<Order> GetOrderList()
        {
            HttpCookie orderCookie = HttpContext.Request.Cookies[Constants.ORDER_COOKIE];
            try
            {
                List<Order> list = new List<Order>();
                if (orderCookie != null)
                {
                    if (!string.IsNullOrEmpty(orderCookie.Value))
                    {
                        string[] products = orderCookie.Value.Split('#');
                        foreach (string product in products)
                        {
                            string[] prop = product.Split('@');
                            Order cookieOrder = new Order();
                            cookieOrder.Id = int.Parse(prop[0]);
                            cookieOrder.Quantity = int.Parse(prop[2]);
                            cookieOrder.Position = int.Parse(prop[3]);

                            Partner partner = new PartnerDao().GetByID(cookieOrder.Id);
                            cookieOrder.Image = partner.Logo;
                            cookieOrder.ProductName = partner.PartnerName;
                            cookieOrder.Price = partner.CurrentPrice.HasValue ? partner.CurrentPrice.Value : 0;
                            cookieOrder.SubTotal = (cookieOrder.Price * cookieOrder.Quantity);
                            list.Add(cookieOrder);
                        }
                    }
                }

                return list;
            }
            catch
            {
                orderCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(orderCookie);
                return new List<Order>();
            }
        }

    }
}
